Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

167
Visualizações
Best way to ensure multiple states are updated and call a function once all states updated [React Functional component]

In my use case there are some controlled input components that stores data in states. When I change one of the dropdown input, it changes 3 more states and triggers an API call. How can I ensure that the 3 states are updated before making the API call ? I am using react functional component.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Option 1

If you're using React 18 and you call those 3 setState(...) within the same function, those states are guaranteed to be updated in the next re-render thanks to automatic batching.

So in this case you can just use an useEffect on any of these 3 states, and call the API in that effect. Check this sandbox for a simple example.

Option 2

For people using React 17 or earlier, you still got auto batching, but only inside React event handlers (please refer to this awesome answer). If you're updating states outside React event handlers, the easiest way is, instead of useState three times, you just put those states in a single state in the first place to make sure they will be updated at the same time, because they are in the same state.

For example:

const [state, setState] = useState({
  state0: 0,
  state1: 'a',
  state2: true,
})

useEffect(() => {
  // Call API here
}, [state])
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda